<template lang="pug">
  el-upload(
    ref="uploadFile"
    :class="!avatarFlag ? '' : 'avatar-uploader'"
    :action="action || BASE_URL + 'file/upload'"
    :limit="limit"
    :name="name"
    :headers="headers"
    :file-list="fileList"
    :on-exceed="exceedHandle"
    :before-upload="beforeUpload"
    :on-success="onSuccess"
    v-bind="$attrs"
    with-credentials
  )
    slot
      el-button(:size="btnSize" type="primary" v-if="!avatarFlag" :loading="uploading")
        //- i(class="mr5 f16" v-if="!noIcon" :class="icon ? icon : 'el-icon-upload'")
        | {{btnText}}
      span.ml5.f12.c_secondary(v-if="suffix") {{suffix}}
      img(
        :src="imageUrl"
        class="avatar"
        v-if="avatarFlag && fileList.length > 0"
        )
      i(v-if="avatarFlag && fileList.length === 0" class="avatar-uploader-icon" :class="uploading ? 'el-icon-loading' : 'el-icon-plus'")
</template>
<script>
import AImage from '../Image'
export default {
  name: 'UploadFile',
  components: {
    AImage
  },
  props: {
    icon: {
      type: String,
      default: ''
    },
    suffix: {
      type: String,
      default: ''
    },
    action: {
      type: String,
      default: ''
    },
    // 是否异步上传
    async: {
      type: Boolean,
      default: false
    },
    // 是否可以重复上传
    canRepeat: {
      type: Boolean,
      default: false
    },
    avatarFlag: {
      type: Boolean,
      default: false
    },
    noIcon: {
      type: Boolean,
      default: false
    },
    name: {
      type: String,
      default: 'file'
    },
    filedList: {
      type: Array,
      default: () => []
    },
    limitSize: {
      type: Number,
      default: 0
    },
    limit: {
      type: Number,
      default: 0
    },
    btnSize: {
      type: String,
      default: 'small'
    },
    btnText: {
      type: String,
      default: '点击上传'
    },
    rest: {
      type: Object,
      default: () => {}
    },
    success: {
      type: Function,
      default: null
    },
    remove: {
      type: Function,
      default: null
    },
    progress: {
      type: Function,
      default: null
    },
    change: {
      type: Function,
      default: null
    }
  },
  data () {
    return {
      uploading: false
    }
  },
  created () {
    console.log(this.action)
  },
  computed: {
    headers () {
      return {
        'X-XSRF-TOKEN': this._csrf
      }
    },
    fileList: {
      get () {
        return this.filedList
      },
      set (val) {
        console.log(val)
        this.$emit('update:filedList', val)
      }
    },
    imageUrl () {
      let url = ''
      if (this.avatarFlag) {
        const fileObj = this.fileList.length > 0 ? this.fileList[this.fileList.length - 1] : {}
        if (fileObj.response && fileObj.response.code === 0) {
          url = this.BASE_URL + 'file/download/' + fileObj.response.data + '?_csrf=' + this._csrf
        }
        if (fileObj.url) {
          url = fileObj.url
        }
      }
      return url
    }
  },
  methods: {
    onSuccess (response, file, fileList) {
      this.fileList = fileList
      if (this.success) {
        this.success({ file, fileList })
      }
      this.$emit('success', fileList)
    },
    onRemove (file, fileList) {
      this.fileList = fileList
      if (this.remove) {
        this.remove({ file, fileList })
      }
      this.$emit('remove', file)
    },
    onProgress (event, file) {
      this.uploading = true
      if (this.progress) {
        this.progress({ event, file })
      }
      this.$emit('progress', { event, file })
    },
    onChange (file) {
      this.uploading = false
      if (this.change) {
        this.change({ event, file })
      }
      this.$emit('change', file)
    },
    exceedHandle () {
      this.$message.error('文件超出个数限制')
    },
    beforeUpload (file) {
      const { limitSize, limit, async, name, rest, canRepeat } = this.$props
      const { fileList } = this
      return new Promise((resolve, reject) => {
        const total = fileList.length + 1

        if (!canRepeat) {
          for (let i = 0; i < fileList.length; i++) {
            if (fileList[i].raw && fileList[i].raw.name === file.name && fileList[i].raw.size === file.size) {
              this.$message.error('请不要上传重复附件', 2)
              reject(new Error())
            }
          }
        }

        // 判断上传个数
        if (limit && total > limit) {
          this.$message.error('最多只能上传' + limit + '张', 2)
          reject(new Error())
          return false
        }

        // 判断上传文件大小
        if (limitSize && file.size / 1024 / 1024 > limitSize) {
          this.$message.error('文件大小不能超过 ' + limitSize + 'MB!')
          return false
        }

        // 判断是否执行上传拦截
        if (async) {
          // 根据后台需求数据格式
          const form = new FormData()
          // 文件对象
          form.append(name, file)
          // 项目封装的请求方法，下面做简单介绍
          this.$emit('uploadFile', form, rest)
          reject(new Error())
          return
        }

        resolve()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader {
  /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
}
.avatar-uploader .el-upload:hover {
  // border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 180px;
  height: 180px;
  line-height: 180px;
  text-align: center;
}
.avatar {
  width: 180px;
  max-width: 180px;
  height: 180px;
  display: block;
}
</style>
